//
//  EditionVC.m
//  运营管理系统
//
//  Created by 杨毅 on 16/10/31.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "EditionVC.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "MBProgressHUD.h"
@interface EditionVC ()
{
    NSString *_versionStr;
    NSString *_releaseNotes;
}
@property (nonatomic,strong)AFHTTPSessionManager *manager;
@end

@implementation EditionVC
- (AFHTTPSessionManager *)manager{
    
    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = UIColorFromRGB(0xf0f0f0);
    self.title = @"运营系统";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    

    [self yunyinAppVersion];
    
}
- (void)initDisc{
    
//    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
//    // 当前应用名称
//    NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];
//    NSLog(@"当前应用名称：%@",appCurName);
//    // 当前应用软件版本  比如：1.0.1
//    NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
//    NSLog(@"当前应用软件版本:%@",appCurVersion);
//    // 当前应用版本号码   int类型
//    NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];
//    NSLog(@"当前应用版本号码：%@",appCurVersionNum);

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((kSCREEN_WIDTH-120)/2, 80, 120, 120)];
    imageView.image = [[UIImage imageNamed:@"yy-icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    imageView.layer.cornerRadius = 5;
    [self.view addSubview:imageView];
    UILabel *eidtiton = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame)+5, kSCREEN_WIDTH, 21)];
    eidtiton.text = [NSString stringWithFormat:@"当前版本:V%@",_versionStr];
    eidtiton.textColor = UIColorFromRGB(0x4d4d4d);
    eidtiton.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:eidtiton];

    UILabel *discreb = [[UILabel alloc]initWithFrame:CGRectZero];
    discreb.text = _releaseNotes;
    discreb.textColor = UIColorFromRGB(0x4d4d4d);
    discreb.numberOfLines = 0;
    discreb.adjustsFontSizeToFitWidth = YES;
    discreb.font = [UIFont systemFontOfSize:15.0];
    [self.view addSubview:discreb];
    CGRect rect = [discreb.text boundingRectWithSize:CGSizeMake(kSCREEN_WIDTH-20, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:discreb.font,NSFontAttributeName, nil] context:nil];
    CGFloat height = rect.size.height;
    discreb.frame = CGRectMake(10, CGRectGetMaxY(eidtiton.frame)+5, kSCREEN_WIDTH-20, height);
}
- (void)yunyinAppVersion{
    //https://itunes.apple.com/cn/lookup?id=1176817914 自己的
    //http://itunes.apple.com/cn/lookup?id=1093039842

//    NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=1174159781"];微信
//    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//    [request setHTTPMethod:@"POST"];
//    NSURLSession *session = [NSURLSession sharedSession];
//    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
//                NSLog(@"%@",dic);
//    }];
//    [task resume];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:@"https://itunes.apple.com/cn/lookup?id=1176817914" parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
       
        NSArray *arr = [dic objectForKey:@"results"];
        if (arr.count == 0) {
            UIImageView *imageCry = [[UIImageView alloc]init];
            imageCry.image = [[UIImage imageNamed:@"img_bad_face"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
            [self.view addSubview:imageCry];
            [imageCry mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self.view);
                make.size.mas_equalTo(CGSizeMake(180, 180));
            }];
            
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"APP暂未上架或没找到APP" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了知道了");
               
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];

        }else{
        NSDictionary *data = [arr firstObject];
        _versionStr = [data objectForKey:@"version"];
        NSString *trackViewUrl = [data objectForKey:@"trackViewUrl"];
        _releaseNotes = [data objectForKey:@"releaseNotes"];//更新日志
        NSString* thisVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        [self initDisc];
        /*
         判断，如果当前版本与发布版本不同，则进入更新。如果相等，那么当前就是最高版本
         */
            
        if ([self compareVersionsFormAppStore:_versionStr WithAppVersion:thisVersion]) {
            UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"发现新版本:%@",_versionStr] message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"下次再说" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了取消");
            }];
            
            UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"去更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                NSLog(@"点击了知道了");
                NSURL * url = [NSURL URLWithString:trackViewUrl];//itunesURL = trackViewUrl的内容
                [[UIApplication sharedApplication] openURL:url];
            }];
            [alertVC addAction:cancelAction];
            [alertVC addAction:OKAction];
            [self presentViewController:alertVC animated:YES completion:nil];
        }
    }
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500 || status == 0) {
            [self showAlert:@"温馨提示" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"温馨提示" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];

}
//比较版本的方法，在这里我用的是Version来比较的
- (BOOL)compareVersionsFormAppStore:(NSString*)AppStoreVersion WithAppVersion:(NSString*)AppVersion{
    
    BOOL littleSunResult = false;
    
    NSMutableArray* a = (NSMutableArray*) [AppStoreVersion componentsSeparatedByString: @"."];
    NSMutableArray* b = (NSMutableArray*) [AppVersion componentsSeparatedByString: @"."];
    
    while (a.count < b.count) { [a addObject: @"0"]; }
    while (b.count < a.count) { [b addObject: @"0"]; }
    
    for (int j = 0; j<a.count; j++) {
        if ([[a objectAtIndex:j] integerValue] > [[b objectAtIndex:j] integerValue]) {
            littleSunResult = true;
            break;
        }else if([[a objectAtIndex:j] integerValue] < [[b objectAtIndex:j] integerValue]){
            littleSunResult = false;
            break;
        }else{
            littleSunResult = false;
        }
    }
    return littleSunResult;//true就是有新版本，false就是没有新版本
    
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
